package com.tuanzi.loan.business.repository.family.impl;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.repository.family.custom.LoanApiOrderRepositoryCustom;
import com.tuanzi.loan.business.service.system.DictionaryService;
import com.tuanzi.loan.core.repository.JOOQBaseRepository;
import com.tuanzi.loan.generated.jooq.loan.tables.LoanApiOrder;
import com.tuanzi.loan.vo.request.family.LoanApiOrderSearchRequest;
import com.tuanzi.loan.vo.response.family.LoanApiOrderSearchResponse;
import com.tuanzi.server.loan_base.constant.IOrderStatus;
import com.tuanzi.server.loan_base.util.PhoneNumNideUtil;
import org.jooq.Record;
import org.jooq.RecordMapper;
import org.jooq.Table;
import org.jooq.impl.TableImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.tuanzi.loan.business.constants.DictionaryCode.WHOLEPROCESSOWNER;
import static com.tuanzi.loan.generated.jooq.loan.tables.LoanWholeRepayDetail.LOAN_WHOLE_REPAY_DETAIL;


@SuppressWarnings({ "rawtypes" })
public class LoanApiOrderRepositoryImpl extends JOOQBaseRepository implements LoanApiOrderRepositoryCustom {
    @Autowired
    DictionaryService dictionaryService;
	@Override
	protected TableImpl getTable() {
		return LoanApiOrder.LOAN_API_ORDER;
	}
	@Override
	public Page<LoanApiOrderSearchResponse> list(LoanApiOrderSearchRequest searchRequest, Pageable pageable) {
        Table SECOND = dslContext.select(LOAN_WHOLE_REPAY_DETAIL.CURRENT_PERIOD,LOAN_WHOLE_REPAY_DETAIL.ORDER_ID
                ,LOAN_WHOLE_REPAY_DETAIL.REPAY_STATUS,LOAN_WHOLE_REPAY_DETAIL.EXCEED_STATUS)
                .from(LOAN_WHOLE_REPAY_DETAIL)
                .where(LOAN_WHOLE_REPAY_DETAIL.CURRENT_FLAG.eq((byte) 1)).asTable("SECOND");

        fields();
        leftJoin(SECOND,LoanApiOrder.LOAN_API_ORDER.ID.eq(SECOND.field("order_id")));
        List<Integer> typeList = Lists.newArrayList();
        for (Dictionary dictionary:dictionaryService.findAllByCode(WHOLEPROCESSOWNER)) {
            typeList.add(Integer.valueOf(dictionary.getName()));
        }
        in(LoanApiOrder.LOAN_API_ORDER.TYPE, typeList);
	    eq(LoanApiOrder.LOAN_API_ORDER.ID, searchRequest.getId());
		eq(LoanApiOrder.LOAN_API_ORDER.PETNAME, searchRequest.getPetname());
		eq(LoanApiOrder.LOAN_API_ORDER.TYPE, searchRequest.getType());
		contains(LoanApiOrder.LOAN_API_ORDER.MOBNUM, searchRequest.getMobnum());
		eq(LoanApiOrder.LOAN_API_ORDER.IDCARD, searchRequest.getIdCard());
        eq(LoanApiOrder.LOAN_API_ORDER.PRODUCT_ID,searchRequest.getProductid());
        eq(LoanApiOrder.LOAN_API_ORDER.CHANNEL,searchRequest.getChannel());
        notIn(LoanApiOrder.LOAN_API_ORDER.STATUS
				,Arrays.asList(new String[]{String.valueOf(IOrderStatus.INIT), String.valueOf(IOrderStatus.VALIDATE), String.valueOf(IOrderStatus.INIT_REVIEW), String.valueOf(IOrderStatus.AUTH_SUCCESS), String.valueOf(IOrderStatus.DIVERSION)}));
		if (Objects.nonNull(searchRequest.getStatus())){
            in(LoanApiOrder.LOAN_API_ORDER.STATUS, statusList(searchRequest.getStatus()));
        }
		eq(LoanApiOrder.LOAN_API_ORDER.CHANNEL_FROM,searchRequest.getChannelFrom());
		if (Objects.nonNull(searchRequest.getStartTime())){
		    ge(LoanApiOrder.LOAN_API_ORDER.CTIME, searchRequest.getStartTime());
        }
        if (Objects.nonNull(searchRequest.getEndTime())){
		    le(LoanApiOrder.LOAN_API_ORDER.CTIME,searchRequest.getEndTime());
        }
		orderBy(LoanApiOrder.LOAN_API_ORDER.CTIME, Sort.Direction.DESC);
		return search(pageable, new LoanApiOrderSearchResponseRecordMapper());
	}
	
	private final class LoanApiOrderSearchResponseRecordMapper implements RecordMapper<Record, LoanApiOrderSearchResponse> {

		@Override
		public LoanApiOrderSearchResponse map(Record record) {
			
			LoanApiOrderSearchResponse response = new LoanApiOrderSearchResponse();
			response.setId(record.get(LoanApiOrder.LOAN_API_ORDER.ID));
			response.setMobnum(PhoneNumNideUtil.hideNum(record.get(LoanApiOrder.LOAN_API_ORDER.MOBNUM)));
			response.setPetname(PhoneNumNideUtil.hideName(record.get(LoanApiOrder.LOAN_API_ORDER.PETNAME)));
			response.setIdCard(PhoneNumNideUtil.hideIdCard(record.get(LoanApiOrder.LOAN_API_ORDER.IDCARD)));
			response.setAmount(record.get(LoanApiOrder.LOAN_API_ORDER.AMOUNT));
			response.setPeroid(record.get(LoanApiOrder.LOAN_API_ORDER.PEROID));
			response.setLoanAmount(record.get(LoanApiOrder.LOAN_API_ORDER.LOAN_AMOUNT));
			response.setType(record.get(LoanApiOrder.LOAN_API_ORDER.TYPE));
			response.setStatus(record.get(LoanApiOrder.LOAN_API_ORDER.STATUS));
			response.setCtime(record.get(LoanApiOrder.LOAN_API_ORDER.CTIME));
			response.setTransactionTime(record.get(LoanApiOrder.LOAN_API_ORDER.TRANSACTION_TIME));
			response.setChannelFrom(record.get(LoanApiOrder.LOAN_API_ORDER.CHANNEL_FROM));
            response.setCurrent_period(record.get(LOAN_WHOLE_REPAY_DETAIL.CURRENT_PERIOD));
            response.setExceed_status(record.get(LOAN_WHOLE_REPAY_DETAIL.EXCEED_STATUS));
			response.setRepay_status(record.get(LOAN_WHOLE_REPAY_DETAIL.REPAY_STATUS));
			response.setProductId(record.get(LoanApiOrder.LOAN_API_ORDER.PRODUCT_ID));
			response.setChannel(record.get(LoanApiOrder.LOAN_API_ORDER.CHANNEL));
			return response;
		}
	}

	private List<Integer> statusList(Integer status){
        switch (status){
			case IOrderStatus.IN_REVIEW: case IOrderStatus.SUCCESS: case IOrderStatus.SEND_DT_INFO:
				//待确认
				return Arrays.asList(new Integer[]{IOrderStatus.IN_REVIEW,IOrderStatus.SUCCESS,IOrderStatus.SEND_DT_INFO});
            case IOrderStatus.CANCEL: case IOrderStatus.FAIL: case IOrderStatus.USER_CANCEL: case IOrderStatus.LOAN_FAIL:
                //未通过
                return Arrays.asList(new Integer[]{IOrderStatus.CANCEL,IOrderStatus.FAIL,IOrderStatus.USER_CANCEL,IOrderStatus.LOAN_FAIL});
            case IOrderStatus.SIGN:
                //待放款
                return Arrays.asList(new Integer[]{IOrderStatus.SIGN});
            case IOrderStatus.LOAN: case IOrderStatus.OVERDUE: case IOrderStatus.GRACE_PERIOD: case IOrderStatus.REPAYMENTS:
                //待还款
                return Arrays.asList(new Integer[]{IOrderStatus.LOAN,IOrderStatus.OVERDUE,IOrderStatus.GRACE_PERIOD,IOrderStatus.REPAYMENTS});
            case IOrderStatus.CLOSED_ACCOUNT: return Arrays.asList(new Integer[]{IOrderStatus.CLOSED_ACCOUNT}); //已结清
        }
        return null;
    }


}
